package cn.school.web;

import cn.school.entity.Subject;
import cn.school.service.GradeService;
import cn.school.service.SubjectService;
import cn.school.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author oldliu
 * @since 1.0
 */
@WebServlet(name = "updateSubject", urlPatterns = {"/toUpdateSubject", "/updateSubject"})
public class SubjectUpdateServlet extends HttpServlet {
    @Override//toUpdateSubject执行这个
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        long id = StringUtil.toLong(req.getParameter("id"));
        Subject sub = SubjectService.INST.get(id);
        if(sub==null){
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().println("<script>alert('信息不存在！');history.back();</script>");
            return;
        }
        req.setAttribute("subject",sub);

        req.setAttribute("grades", GradeService.INST.findALL());

        req.getRequestDispatcher("/WEB-INF/jsp/subjectupdate.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String subname=req.getParameter("subjectname");
        int classhour= StringUtil.toInt(req.getParameter("classhour"));
        long gradeid= StringUtil.toLong(req.getParameter("gradeid"));
        long id= StringUtil.toLong(req.getParameter("id"));
        Subject subject=new Subject(id,gradeid,subname,classhour);
        int r = SubjectService.INST.update(subject);
        if(r<1){
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().println("<script>alert('修改失败！');history.back();</script>");
            return;
        }
        req.getSession().setAttribute("msg","修改成功");
        resp.sendRedirect("subjectServlet");
    }
}
